package com.achieve.wx.service;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.shortlink.GenerateShortLinkRequest;
import com.achieve.wx.domain.WechatGenerateQrCodeParam;
import com.achieve.wx.domain.WechatGenerateShortLinkParam;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class WxMaManagerService {
    @Autowired
    private WxMaService wxMaService;

    /**
     * 生成小程序码
     */
    @SneakyThrows
    public byte[] createWxaCode(WechatGenerateQrCodeParam param) {
        WxMaService service = wxMaService.switchoverTo(param.getAppKey());

        try {
            return service.getQrcodeService().createWxaCodeUnlimitBytes(param.getScene(), param.getPage(), param.getCheckPath(), param.getEnvVersion(),
                    param.getWidth(), param.getAutoColor(), param.getLineColor(), param.getIsHyaline());
        } catch (Exception e) {
            if (isTokenInvalid(e)) {
                // 如果token无效，刷新一次后重试
                service.getWxMaConfig().expireAccessToken();
                return service.getQrcodeService().createWxaCodeUnlimitBytes(param.getScene(), param.getPage(), param.getCheckPath(), param.getEnvVersion(),
                        param.getWidth(), param.getAutoColor(), param.getLineColor(), param.getIsHyaline());
            }
            throw new RuntimeException("生成小程序码失败", e);
        }
    }

    /**
     * 生成短链接
     */
    @SneakyThrows
    public String createShortLink(WechatGenerateShortLinkParam param) {
        WxMaService service = wxMaService.switchoverTo(param.getAppKey());
        // 短期有效
        GenerateShortLinkRequest shortLinkRequest = GenerateShortLinkRequest.builder().pageUrl(param.getPageUrl()).isPermanent(false).build();

        try {
            return service.getLinkService().generateShortLink(shortLinkRequest);
        } catch (Exception e) {
            if (isTokenInvalid(e)) {
                // 如果token无效，刷新一次后重试
                service.getWxMaConfig().expireAccessToken();
                return service.getLinkService().generateShortLink(shortLinkRequest);
            }
            throw new RuntimeException("生成短链接失败", e);
        }
    }

    /**
     * 判断是否是token无效的错误
     */
    private boolean isTokenInvalid(Exception e) {
        String errorMsg = e.getMessage();
        return StringUtils.containsIgnoreCase(errorMsg, "access_token")
                && (StringUtils.containsIgnoreCase(errorMsg, "invalid")
                || StringUtils.containsIgnoreCase(errorMsg, "expired"));
    }
}
